<?php


namespace App\Services;


use App\Models\Role;
use App\Service\Service;
use Dingo\Api\Http\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Class RoleService
 * @property string $name
 * @property string $desc
 * @property array $permissions
 * @property string $keywords
 * @package App\Services
 * @author thanatos thanatos915@163.com
 */
class RoleService extends Service
{
    /**
     * 角色列表
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     * @author thanatos thanatos915@163.com
     */
    public static function search(Request $request)
    {
        $service = static::loadParams($request, [
            'keywords' => 'string'
        ]);

        $query = Role::orderBy('created_at', 'desc');

        if ($service->keywords) {
            $query->where('name', 'like', '%'. $service->keywords .'%');
        }
        return $query->paginate();
    }

    /**
     * 角色详情
     * @author thanatos thanatos915@163.com
     */
    public static function info($id)
    {
        $role = Role::find($id);

        if (empty($role)) {
            throw new BadRequestHttpException("角色不存在");
        }

        $role->load('permissions');
        return $role;
    }

    /**
     * 创建或修改角色
     * @param Request $request
     * @param int $id
     * @return Role|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     * @author thanatos thanatos915@163.com
     */
    public static function createAndUpdate(Request $request, $id = 0)
    {
        $service = self::loadParams($request, [
            'name' => 'required|string',
            'desc' => 'required|string',
            'permissions' => 'required|array',
        ]);

        if ($id > 0) {
            $model = Role::find($id);
        }
        if (empty($model)) {
            $model = new Role();
        }

        $model->fill($service->getAttributes());
        $model->guard_name = config('auth.defaults.guard');
        $model->save();

        $model->syncPermissions($service->permissions);
        return $model;
    }

    /**
     * 删除用户
     * @param $id
     * @author thanatos thanatos915@163.com
     */
    public static function delete($id)
    {
        $role = Role::find($id);
        if (empty($role)) {
            throw new BadRequestHttpException("角色不存在");
        }

        $role->delete();
    }

}
